/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc;

import com.je.common.base.DynaBean;
import com.je.common.base.JsonAssist;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.EntityUtils;
import com.je.common.base.util.StringUtil;
import com.je.meta.cache.table.DynaCache;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@RpcSchema(schemaId = "dynaModelRpcService")
public class DynaModelRpcServiceImpl implements DynaModelRpcService {

    @Autowired
    private DynaCache dynaCache;
    @Autowired
    private BeanService beanService;

    /**
     * 构建前端使用的模型
     *
     * @param tableName 表明
     * @param modelName TODO 暂不明确
     * @param doTree    TODO 暂不明确
     * @param excludes  TODO 暂不明确
     * @return
     */
    @Override
    public String buildModel(String tableName, String modelName, Boolean doTree, String excludes) {
        JsonAssist jsonAssist = JsonAssist.getInstance();
        // 实体方式
        String modelStr = "";
        if (StringUtil.isNotEmpty(modelName)) {
            modelStr = dynaCache.getCacheValue(modelName);
            if (StringUtil.isEmpty(modelStr)) {
                Field[] fields = EntityUtils.getInstance().getEntityInfo(modelName).getAllBaseFields();
                if (StringUtil.isNotEmpty(excludes)) {
                    modelStr = jsonAssist.getMoldeJsonByFields4Extjs(modelName, fields, excludes);
                } else {
                    modelStr = jsonAssist.getMoldeJsonByFields4Extjs(modelName, fields, null);
                }
                dynaCache.putCache(modelName, modelStr);
            }
            // DynaBean方式
        } else if (StringUtil.isNotEmpty(tableName)) {
            modelStr = dynaCache.getCacheValue(tableName);
            if (StringUtil.isEmpty(modelStr) || doTree) {
                DynaBean resourceTable = beanService.getResourceTable(tableName);
                if (null != resourceTable && null != resourceTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS)) {
                    List<DynaBean> columns = resourceTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
                    List<DynaBean> resColumns = new ArrayList<DynaBean>();
                    resColumns.addAll(columns);
                    if (doTree) {
                        buildTreeField(resColumns);
                    }
                    modelStr = jsonAssist.getMoldeJsonByFields4Extjs(tableName, resColumns, null);
                    dynaCache.putCache(tableName, modelStr);
                } else {
                    throw new PlatformException("根据表名获取列信息异常!", PlatformExceptionEnum.JE_CORE_DYNABEAN_MODEL_ERROR, new Object[]{tableName, modelName, doTree, excludes});
//					modelStr = ConstantVars.BLANK_STR;
                }
            }
        } else {
            throw new PlatformException("传入实体名和表名失败，无法获取字段信息!", PlatformExceptionEnum.JE_CORE_DYNABEAN_MODEL_ERROR, new Object[]{tableName, modelName, doTree, excludes});
        }
        return modelStr;
    }

    /**
     * 构建树形字段
     *
     * @param columns
     */
    private void buildTreeField(List<DynaBean> columns) {
        String[] fields = new String[]{"id", "text", "cls", "leaf", "href", "hrefTarget", "description", "code", "icon", "iconCls", "bigIcon", "bigIconCls", "parent", "nodeInfo", "nodeInfoType", "disabled", "nodePath"};
        for (String field : fields) {
            DynaBean column = new DynaBean("JE_CORE_TABLECOLUMN", false);
            column.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
            column.set("TABLECOLUMN_CODE", field);
            if ("leaf".equals(field)) {
                column.set("TABLECOLUMN_TYPE", "boolean");
            } else {
                column.set("TABLECOLUMN_TYPE", "varchar255");
            }
            columns.add(column);
        }
    }

}
